<?php

namespace App\Imports;

use App\Classify;
use App\Enterprise;
use App\Merchant;
use App\MerchantMedicine;
use App\MerchantMedicineImg;
use App\MerchantMedicineXClassify;
use App\SystemMedicine;
use App\SystemMedicineImg;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\WithChunkReading;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Row;

class ExcelToNoneStandardMedicine implements OnEachRow,WithHeadingRow,WithChunkReading
{

    protected $allowMerchantIdArr   = [];
    protected $storeIdCache         = [];
    protected $classifyCache        = [];
    protected $unknownRow           = [];
    protected $addFirstClassify     = [];
    protected $addSecondClassify    = [];
    protected $addMedicineNum       = 0;
    protected $changeMedicineNum       = 0;
    protected $i                    = 1;
    protected $errorMessage         = [];
    protected $enterprise_id        = 0;
    protected $merchantMedicineUpcTemp = [];
    protected $defaultMerchantId    = 0;

    public function __construct($enterprise_id,$defaultMerchantId = 0)
    {
        $this->allowMerchantIdArr = Enterprise::getEnterpriseMerchantIds($enterprise_id);
        $this->enterprise_id            = $enterprise_id;
        $this->defaultMerchantId        = $defaultMerchantId;
    }



    public function updateDatabase($row){
        /** 取值 */
        $upc                =trim($row['bar_code']) ?? '';
        $store              =trim($row['store']) ?? '';
        $first_classify     =trim($row['first_classify']) ?? '';
        $second_classify    =trim($row['second_classify']) ?? '';
        $selling_price      =trim($row['selling_price']) ?? '';
        $stock              =trim($row['stock']) ?? 0;
        $is_shop            =trim($row['is_shop']) ?? 0;
        $sort               =trim($row['sort']) ?? 0;

        if (!$upc || $upc == 'upc码'){
            $this->i++;
            return null;
        }

        if ($store){
            //门店缓存
            $storeKey = md5($store);
            if (!isset($this->storeIdCache[$storeKey])){
                //查库
                $thisMerchant = Merchant::whereEnterpriseId($this->enterprise_id)
                    ->whereName($store)
                    ->first();
                if(!$thisMerchant){
                    array_push($this->errorMessage,"第$this->i 行，当前企业没有该门店,门店名称：$store");
                    return null;
                }

                $this->storeIdCache[$storeKey] = $thisMerchant->id ?? 0;
            }

            if (!in_array($this->storeIdCache[$storeKey],$this->allowMerchantIdArr)){
                array_push($this->errorMessage,"第$this->i 行，当前企业没有该门店,门店名称：$store");
                return null;
            }
        } elseif (!$this->defaultMerchantId){

        } else {
            array_push($this->errorMessage,"第$this->i 行，未填写门店名称");
            return null;
        }

        if ($first_classify){
            //一级分类缓存
            $classifyKey = md5($first_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($first_classify)
                    ->first();
                if (!$thisClassify){
                    $thisClassify = new Classify();
                    $thisClassify->enterprise_id = $this->enterprise_id;
                    $thisClassify->name          = $first_classify;
                    $thisClassify->merchant_id   = $this->storeIdCache[$storeKey] ?? 0;
                    $thisClassify->type          = 'selling';
                    $thisClassify->save();
                }
                $this->classifyCache[$classifyKey] = $thisClassify->id;
            }
        }

        if ($second_classify){
            //二级分类缓存
            $classifyKey = md5($second_classify);
            if (!isset($this->classifyCache[$classifyKey])){
                //查库
                $thisClassify = Classify::whereEnterpriseId($this->enterprise_id)
                    ->whereMerchantId($store ? $this->storeIdCache[$storeKey] : 0)
                    ->whereType('selling')
                    ->whereName($second_classify)
                    ->first();
                if (!$thisClassify){
                    $thisClassify = new Classify();
                    $thisClassify->enterprise_id = $this->enterprise_id;
                    $thisClassify->name          = $first_classify;
                    $thisClassify->merchant_id   = $this->storeIdCache[$storeKey] ?? 0;
                    $thisClassify->type          = 'selling';
                    $thisClassify->save();
                }
                $this->classifyCache[$classifyKey] = $thisClassify ? $thisClassify->name : '';
            }
        }
        if ($upc){
            $exist = MerchantMedicine::whereMerchantId($this->storeIdCache[$storeKey])
                ->whereUpc($upc)
                ->first();
            if (!$exist){
                //新增
                $systemMedicine = SystemMedicine::whereStatus(1)
                    ->whereUpc($upc)
                    ->first();

                if ($systemMedicine){
                    //TODO 系统药品库商品
                    $newMerchantMedicine = new MerchantMedicine();
                    $newMerchantMedicine->upc = $upc;
                    $newMerchantMedicine->name = $systemMedicine->name;
                    $newMerchantMedicine->merchant_id = $this->storeIdCache[$storeKey];
                    $newMerchantMedicine->approval_number = $systemMedicine->approval_number;
                    $newMerchantMedicine->specification = $systemMedicine->specification;
                    $newMerchantMedicine->selling_price = $selling_price ? $selling_price : 0;
                    $newMerchantMedicine->stock = $stock ? $stock : 0;
                    $newMerchantMedicine->manufacturer = $systemMedicine->manufacturer;
                    $newMerchantMedicine->manufacturer_address = $systemMedicine->manufacturer_address;
                    $newMerchantMedicine->manufacturer_contact = $systemMedicine->manufacturer_contact;
                    $newMerchantMedicine->electronic_regulatory_code = $systemMedicine->electronic_regulatory_code;
                    $newMerchantMedicine->usage_and_dosage = $systemMedicine->usage_and_dosage;
                    $newMerchantMedicine->indications = $systemMedicine->indications;
                    $newMerchantMedicine->adapt_to_the_crowd = $systemMedicine->adapt_to_the_crowd;
                    $newMerchantMedicine->component = $systemMedicine->component;
                    $newMerchantMedicine->adverse_reactions = $systemMedicine->adverse_reactions;
                    $newMerchantMedicine->contraindications = $systemMedicine->contraindications;
                    $newMerchantMedicine->precautions = $systemMedicine->precautions;
                    $newMerchantMedicine->interaction = $systemMedicine->interaction;
                    $newMerchantMedicine->medication_for_children = $systemMedicine->medication_for_children;
                    $newMerchantMedicine->medication_for_pregnancy_x_lactation = $systemMedicine->medication_for_pregnancy_x_lactation;
                    $newMerchantMedicine->medication_for_aged = $systemMedicine->medication_for_aged;
                    $newMerchantMedicine->properties = $systemMedicine->properties;
                    $newMerchantMedicine->packing = $systemMedicine->packing;
                    $newMerchantMedicine->dosage_form = $systemMedicine->dosage_form;
                    $newMerchantMedicine->storage = $systemMedicine->storage;
                    $newMerchantMedicine->pharmacological_action = $systemMedicine->pharmacological_action;
                    $newMerchantMedicine->expiry_date = $systemMedicine->expiry_date;
                    $newMerchantMedicine->detail = $systemMedicine->detail;
                    $newMerchantMedicine->is_shop = $is_shop ? $is_shop : 0;
                    $newMerchantMedicine->sort = $sort ? $sort : 0;
                    $newMerchantMedicine->save();
                    if ($this->classifyCache[md5($first_classify)] != '') {
                        $newMerchantMedicineClassify = new MerchantMedicineXClassify();
                        $newMerchantMedicineClassify->merchant_medicine_id  = $newMerchantMedicine->id;
                        $newMerchantMedicineClassify->classify_id           = $this->classifyCache[md5($first_classify)];
                        $newMerchantMedicineClassify->save();
                    }
                    if ($this->classifyCache[md5($second_classify)] != ''){
                        $newMerchantMedicineClassifyTwo = new MerchantMedicineXClassify();
                        $newMerchantMedicineClassifyTwo->merchant_medicine_id = $newMerchantMedicine->id;
                        $newMerchantMedicineClassifyTwo->classify_id = $this->classifyCache[md5($second_classify)];
                        $newMerchantMedicineClassifyTwo->save();
                    }
                    $systemMedicineImgList = SystemMedicineImg::whereSystemMedicineId($systemMedicine->id)->get();
                    if (count($systemMedicineImgList) > 0) {
                        foreach ($systemMedicineImgList as $item){
                            MerchantMedicineImg::firstOrCreate(
                                ['merchant_medicine_id'=>$newMerchantMedicine->id, 'img_id'=>$item->img_id,],
                                ['sort'=>$item->sort]);
                        }
                    }
                } else {
                    //TODO　非标商品
                    return null;
                }

            } else {
                //修改
                $exist->selling_price = $selling_price ? $selling_price : 0;
                $exist->stock = $stock ? $stock : 0;
                $exist->is_shop = $is_shop ? $is_shop : 0;
                $exist->sort = $sort ? $sort : 0;
                $exist->save();
            }
            //TODO　非标处理
        }
    }


    /**
     * @param Row $row
     */
    public function onRow(Row $row)
    {
        $this->updateDatabase($row);
    }

    public function chunkSize(): int
    {
        // TODO: Implement chunkSize() method.
        return 1000;
    }
}
